<?php

declare(strict_types=1);

namespace app\controller;

use app\BaseController;
use app\model\Users;
use think\exception\ValidateException;
use think\response\Json;
use utils\Auth;

class User extends BaseController
{
    public function index(): Json
    {
        $this->checkLogin();
        if (!$this->auth->check('view_user_list', $this->user->id)) return $this->error('权限不足');
        $condition = $this->request->get();
        $user_list = Users::with(['group', 'profile'])->where($condition)->select();
        return $this->success('success', $user_list);
    }

    public function save(): Json
    {
        $data = $this->request->post();
        try {
            $this->validate($data, \app\validate\User::class);
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        }
        $user = Users::where('card', $data['card'])->find();
        if (!empty($user)) return $this->error('该用户已存在');
        $data['status'] = 0;
        $data['group_id'] = 3;
        $user = Users::create($data);
        $data['profile']['phone'] = $data['phone'];
        $user->profile()->save($data['profile']);
        return $this->success('success', $user);
    }

    public function read($id = 0): Json
    {
        $this->checkLogin();
        if ($id === 0) {
            $id = $this->user->id;
        }
        $user = Users::with(['profile', 'group'])->find($id);
        if (empty($user)) return $this->error('用户不存在');
        return $this->success('success', $user);
    }

    public function login(): Json
    {
        $data = $this->request->post();
        $type = $this->request->post('type');
        if (!in_array($type, ['h5', 'phone'])) return $this->error('数据格式错误');
        $result = Users::login($data);
        if ($result === false) return $this->error('账号或密码错误，也可能不存在或已被封禁');
        if ($type === 'h5') $user = Users::with(['profile', 'group'])->where('card', $data['user'])->find();
        if ($type === 'phone') $user = Users::with(['profile', 'group'])->where('phone', $data['phone'])->find();
        $token = Auth::createToken($user);
        return $this->success('登录成功', [
            'userInfo' => $user,
            'token' => $token
        ]);
    }

    public function logout(): Json
    {
        $this->checkLogin();
        Auth::cancelToken($this->request->token);
        return $this->success('logout success');
    }

    public function apply_pass($id): Json
    {
        if ($this->auth->check('admin', $this->user->id)) {
            $user = Users::find($id);
            $user->password = password_hash(substr($user->card, -6), PASSWORD_DEFAULT);
            $user->status = 1;
            $user->save();
            return $this->success('success');
        } else {
            return $this->error('权限不足');
        }
    }

    public function apply_reject($id): Json
    {
        if ($this->auth->check('admin', $this->user->id)) {
            $user = Users::find($id);
            $user->status = -10;
            $user->save();
            return $this->success('success');
        } else {
            return $this->error('权限不足');
        }
    }

    public function reset_password(): Json
    {
        $this->checkLogin();
        $old_password = $this->request->post('password');
        $new_password = $this->request->post('new_password');
        $confirm_password = $this->request->post('confirm');
        if (!password_verify($old_password, $this->user->password)) return $this->error('密码错误');
        if ($new_password !== $confirm_password) return $this->error('两次密码不一致');
        $this->user->password = password_hash($new_password, PASSWORD_DEFAULT);
        $this->user->save();

        // 删除旧凭证
        Auth::cancelToken($this->token);

        return $this->success('修改成功, 请重新登录');
    }

    public function upload_avatar(): Json
    {
        $this->checkLogin();
        $avatar_key = $this->request->patch('attach_key');
        $this->user->profile->avatar = $avatar_key;
        $this->user->profile->save();
        return $this->success('头像修改完成', $this->user);
    }

    public function reset_phone(): Json
    {
        $this->checkLogin();
        $data = $this->request->patch(['code', 'phone']);
        $_code = cache("reset_phone_sms_code_{$data['phone']}");
        if (empty($_code)) return $this->error('验证码已过期或不存在，请重试');
        if ($_code == $data['code']) {
            $this->user->phone = $data['phone'];
            $this->user->profile->phone = $data['phone'];
            $this->user->profile->save();
            $this->user->save();
            cache("reset_phone_sms_code_{$data['phone']}", null);
            cache("reset_phone_sms_send_{$data['phone']}", null);
            return $this->success('success');
        } else {
            return $this->error('验证码不正确，请重试');
        }
    }

    public function find_password(): Json
    {
        $data = $this->request->post(['phone', 'code']);
        $_code = cache("reset_password_sms_code_{$data['phone']}");
        if (empty($_code)) return $this->error('验证码已过期或不存在，请重试');
        if ($_code == $data['code']) {
            $user = Users::where('phone', $data['phone'])->find();
            if (empty($user)) return $this->error('用户不存在');
            $user->password = password_hash(substr($user->card, -6), PASSWORD_DEFAULT);
            $user->save();
            cache("reset_password_sms_code_{$data['phone']}", null);
            return $this->success('密码已重置为身份证后六位');
        }
        return $this->error('验证码不正确，请重试');
    }

    public function delete($id)
    {
        $this->checkLogin();
        Users::destroy($id);
        return $this->success('success');
    }
}
